#pragma once

#include "Primitive.h"

class Triangle: public Primitive
{
private:
	float x1,y1,z1;
	float x2,y2,z2;
	float x3,y3,z3;
public:
	Triangle() {};
	void render()
	{
		if(getTex() != NULL)
		{
			float dist = calcDistBetweenTwoPoints(x1, y1, z1, x2, y2, z2);
			float dist2 = calcDistBetweenTwoPoints(x1, y1, z1, x3, y3, z3);
			float vec1x = x2 - x1;
			float vec1y = y2 - y1;
			float vec1z = z2 - z1;
			float vec2x = x3 - x1;
			float vec2y = y3 - y1;
			float vec2z = z3 - z1;

			float normalX = vec1x*vec2z - vec1z*vec2y;
			float normalY = vec1z*vec2x - vec1x*vec2z;
			float normalZ = vec1x*vec2y - vec1y*vec2x;

			float AB[3],AC[3];
			AB[0]=(vec1x)/dist;
			AB[1]=(vec1y)/dist;
			AB[2]=(vec1z)/dist;
			AC[0]=(vec2x)/dist2;
			AC[1]=(vec2y)/dist2;
			AC[2]=(vec2z)/dist2;

			float cosAlfa =abs(AB[0]*AC[0]+AB[1]*AC[1]+AB[2]*AC[2]);
			float AD = dist*cosAlfa;
			float AE = dist*sin(acos(cosAlfa));

			float lS = getTex()->getLengthS();
			float lT = getTex()->getLengthT();

			glBindTexture(GL_TEXTURE_2D, getTex()->getTexID());
			glEnable(GL_TEXTURE_2D);
			glBegin(GL_POLYGON);
					glNormal3d(normalX,normalY, normalZ);
					glTexCoord2f(dist/lS, 0.0); glVertex3f(x1, y1, z1);
					glTexCoord2f(AD/lS,AE/lT); glVertex3f(x2, y2, z2); 
					glTexCoord2f(0.0, 0.0);glVertex3f(x3, y3, z3);
			glEnd();
			glDisable(GL_TEXTURE_2D);
		}
		else
		{
			glBegin(GL_POLYGON);
				glVertex3d(x1,y1,z1);
				glVertex3d(x2,y2,z2);
				glVertex3d(x3,y3,z3);
			glEnd();
		}
	}

	void setValues(float _x1, float _y1, float _z1, float _x2, float _y2, float _z2, float _x3, float _y3, float _z3)
	{
		x1 = _x1; x2 = _x2; x3 = _x3;
		y1 = _y1; y2 = _y2; y3 = _y3;
		z1 = _z1; z2 = _z2; z3 = _z3;
	}

	float calcDistBetweenTwoPoints(float _x1, float _y1, float _z1, float _x2, float _y2, float _z2)
	{
		float dx = _x2 - _x1;
		float dy = _y2 - _y1;
		float dz = _z2 - _z1;
		return (float) sqrt( pow(dx, 2) + pow(dy, 2) + pow(dz, 2) );
	}
};
